package com.xingxing.Activity;

import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.model.GradientColor;
import com.google.gson.Gson;
import com.xingxing.Bean.GroupByMonthStatus;
import com.xingxing.Bean.RecordStatus;
import com.xingxing.Interface.OkSuccessInterface;
import com.xingxing.Util.APIConfig;
import com.xingxing.Util.CommonUtils;
import com.xingxing.View.DayAxisValueFormatter;
import com.xingxing.View.MoneyValueFormatter;
import com.xingxing.View.XYMarkerView;
import com.xuexiang.xui.utils.StatusBarUtils;
import com.xuexiang.xui.utils.XToastUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xingxing.Util.CommonUtils.OKJsonPost;

public class MyBillActivity extends AppCompatActivity implements OnChartValueSelectedListener {
    private BarChart chart;
    private TextView thisYearValue;
    private TextView balanceValue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置沉浸式状态栏
        StatusBarUtils.translucent(this);
        //设置黑色字体状态栏
        StatusBarUtils.setStatusBarLightMode(this);
        setContentView(R.layout.activity_my_bill);
        chart = findViewById(R.id.chart);
        thisYearValue = findViewById(R.id.this_year_value);
        balanceValue = findViewById(R.id.balance_value);
        initChartStyle();
        initChartLabel();
        getData();

        Map<String, Object> map = new HashMap<>();
        map.put("userAccount", CommonUtils.GetUserInfo().getUserAccount());
        OKJsonPost(this, new Gson().toJson(map), APIConfig.GetUserBalanceByUserAccount, new OkSuccessInterface() {
            @Override
            public void OnSuccess(String json) {
                Map<String, Object> map = new HashMap<>();
                map = new Gson().fromJson(json, map.getClass());
                if (map.get("status").equals("success")) {
                    balanceValue.setText(map.get("userBalance").toString() + "元");
                } else if (map.get("status").equals("error")) {
                    XToastUtils.info("用户余额失败！");
                }
            }
        });
        chart.setOnChartValueSelectedListener(this);
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        //XToastUtils.toast("选中了,  x轴值:" + e.getX() + ", y轴值:" + e.getY());
    }

    @Override
    public void onNothingSelected() {

    }

    private void getData() {
        Map<String, Object> map = new HashMap<>();
        map.put("userAccount", CommonUtils.GetUserInfo().getUserAccount());
        OKJsonPost(this, new Gson().toJson(map), APIConfig.GroupByMonth, new OkSuccessInterface() {
            @Override
            public void OnSuccess(String json) {
                GroupByMonthStatus status = new Gson().fromJson(json, GroupByMonthStatus.class);
                if (status.getStatus().equals("success")) {
                    CommonUtils.groupByMonthList = (List<RecordStatus>) status.getData();
                    setChartData(12, 50);
                    chart.animateY(2000);// Y 轴动画
                } else if (status.getStatus().equals("error")) {
                    XToastUtils.warning("数据获取失败！");
                }
            }
        });
    }

    /**
     * 初始化图表的样式
     */
    protected void initChartStyle() {
        //关闭描述
        chart.getDescription().setEnabled(false);
        chart.setDrawBarShadow(false);

        //开启在柱状图顶端显示值
        chart.setDrawValueAboveBar(true);
        //设置显示值时，最大的柱数量
        chart.setMaxVisibleValueCount(12);

        //设置不能同时在x轴和y轴上缩放
        chart.setPinchZoom(false);
        //设置不画背景网格
        chart.setDrawGridBackground(false);

        initXYAxisStyle();
    }


    /**
     * 初始化图表X、Y轴的样式
     */
    private void initXYAxisStyle() {
        //设置X轴样式
        ValueFormatter xAxisFormatter = new DayAxisValueFormatter(chart);
        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        //间隔一天显示
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(7);
        xAxis.setValueFormatter(xAxisFormatter);

        //设置Y轴的左侧样式
        ValueFormatter yAxisFormatter = new MoneyValueFormatter("元");
        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setLabelCount(8, false);
        leftAxis.setValueFormatter(yAxisFormatter);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(15f);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        //设置Y轴的右侧样式
        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setDrawGridLines(false);
        rightAxis.setLabelCount(8, false);
        rightAxis.setValueFormatter(yAxisFormatter);
        rightAxis.setSpaceTop(15f);
        rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        //设置图表的数值指示器
        XYMarkerView mv = new XYMarkerView(this, xAxisFormatter, yAxisFormatter);
        mv.setChartView(chart);
        chart.setMarker(mv);
    }


    /**
     * 初始化图表的 标题 样式
     */
    protected void initChartLabel() {
        //设置图表 标题 的样式
        Legend l = chart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setForm(Legend.LegendForm.SQUARE);
        l.setFormSize(9f);
        l.setTextSize(18f);
        l.setXEntrySpace(4f);
    }

    /**
     * 设置图表数据
     *
     * @param count 柱状图中柱的数量
     * @param range
     */
    protected void setChartData(int count, float range) {
        List<BarEntry> values = new ArrayList<>();
        //设置数据源
        float sum = 0.00f;
        for (RecordStatus month : CommonUtils.groupByMonthList) {
            int i = Integer.parseInt(month.getMonth());
            float val = Float.parseFloat(month.getCost());
            sum += val;
            //设置图表，标星
            //values.add(new BarEntry(i, val, getResources().getDrawable(R.drawable.ic_star_green)));
            values.add(new BarEntry(i, val));
        }
        thisYearValue.setText("" + new DecimalFormat(".00").format(sum) + "元");

        BarDataSet set1;

        if (chart.getData() != null && chart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) chart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(values, "2022年消费按月统计");

            //设置是否画出图标
            set1.setDrawIcons(false);

            int startColor1 = ContextCompat.getColor(this, android.R.color.holo_orange_light);
            int startColor2 = ContextCompat.getColor(this, android.R.color.holo_blue_light);
            int startColor3 = ContextCompat.getColor(this, android.R.color.holo_orange_light);
            int startColor4 = ContextCompat.getColor(this, android.R.color.holo_green_light);
            int startColor5 = ContextCompat.getColor(this, android.R.color.holo_red_light);
            int endColor1 = ContextCompat.getColor(this, android.R.color.holo_blue_dark);
            int endColor2 = ContextCompat.getColor(this, android.R.color.holo_purple);
            int endColor3 = ContextCompat.getColor(this, android.R.color.holo_green_dark);
            int endColor4 = ContextCompat.getColor(this, android.R.color.holo_red_dark);
            int endColor5 = ContextCompat.getColor(this, android.R.color.holo_orange_dark);

            List<GradientColor> gradientColors = new ArrayList<>();
            gradientColors.add(new GradientColor(startColor1, endColor1));
            gradientColors.add(new GradientColor(startColor2, endColor2));
            gradientColors.add(new GradientColor(startColor3, endColor3));
            gradientColors.add(new GradientColor(startColor4, endColor4));
            gradientColors.add(new GradientColor(startColor5, endColor5));

            //设置渐变色
            set1.setGradientColors(gradientColors);

            //这里只设置了一组数据
            List<IBarDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(14f);
            data.setBarWidth(0.9f);

            chart.setData(data);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}